<template>
  <div class="lover-container">
    <van-nav-bar fixed :style="isLoverLogin?'color: pink':'color: blue'">
      <template #left>
        <span @click="$router.back()">
          <svg-icon style="margin-left: 10px;" icon-class='fanhui' width="30px" height="30px" class="icon"/>
        </span>
      </template>
      <template #right>
        {{ isLoverLogin ? '对方在线' : '对方不在线' }}
      </template>
      <template #title>
        {{ loverInfo.username }}
      </template>
    </van-nav-bar>

    <!-- 中间 聊天内容区域 -->
    <div class="mainWrap">
      <div class="main" ref="chatRoom">
        <div v-for="(item,index) in chatDataArr" :key="index">
          <div class="leftPerson msg" v-if="item.name===loverInfo.username">
            <van-image
              round
              width="1rem"
              height="1rem"
              fit="cover"
              :src="item.img"
            />
            <div class="conWrap">
              <div class="content">
                <div> {{ item.content }}</div>
                <van-image
                  round
                  width="3rem"
                  height="3rem"
                  fit="cover"
                  :src="item.contentImg"
                  v-if="item.contentImg"
                />
                <span v-for="(item,index) in item.emojiList.split('$').slice(0,-1)" :key="index">
                  <svg-icon style="margin-left: 10px;" :icon-class='item' width="30px" height="30px" class="icon"/>
                </span>
                <span v-if="item.audioData" @click="playAudio">
                  <audio ref="audio" :src="item.audioData" preload></audio>
                  {{ item.duration }}'
                   <svg-icon style="margin-left: 5px; margin-right: 5px;" icon-class='dyvmsyuyinfuwu' width="30px"
                             height="30px"
                             class="icon"/>
                </span>
              </div>
              <div class="msgTime">{{ item.time | toTime }}</div>
            </div>

          </div>
          <div class="rightPerson msg" v-if="item.name===userInfo.username">
            <van-image
              round
              width="1rem"
              height="1rem"
              fit="cover"
              :src="item.img"
            />
            <div class="conWrap">
              <div class="content">
                <div> {{ item.content }}</div>
                <van-image
                  width="3rem"
                  height="3rem"
                  fit="cover"
                  :src="item.contentImg"
                  v-if="item.contentImg"
                />
                <span v-for="(item,index) in item.emojiList.split('$').slice(0,-1)" :key="index">
                  <svg-icon style="margin-left: 10px;" :icon-class='item' width="30px" height="30px" class="icon"/>
                </span>
                <span v-if="item.audioData" @click="playAudio">
                  <audio ref="audio" :src="item.audioData" preload></audio>
                  {{ item.duration }}'
                   <svg-icon style="margin-left: 5px; margin-right: 5px;" icon-class='dyvmsyuyinfuwu' width="30px"
                             height="30px"
                             class="icon"/>
                </span>
              </div>
              <div class="msgTime">{{ item.time | toTime }}</div>
            </div>
          </div>

        </div>
      </div>
    </div>
    <van-overlay :show="isAudioShow">
      <div class="wrapper">
        <span>Duration：{{ recorder.duration.toFixed(2) }}</span>
        <van-image
          class="GIF"
          width="9em"
          height="9em"
          :src="require('@/assets/audio.gif')"/>
        <van-button color="#ac92eb" @click="stopRecordAudio">说完话啦~</van-button>
      </div>
    </van-overlay>
    <!-- 底部 消息编辑区域 -->
    <div class="foot">
      <div class="audio-container">
        <!--        <span>Duration：{{ recorder.duration.toFixed(4) }}</span>-->
      </div>
      <div class="inputBox">
        <input type="file" hidden ref="file" @change="onFileChange"/>
        <span @click="$refs['file'].click()">
          <svg-icon style="margin-right: 5px;" icon-class='xiangpian' width="30px" height="30px" class="icon"/>
        </span>
        <input type="text" class="sendMsg" v-model="sendMsg" placeholder="输入你想对Ta说的~"/>
        <span @click="send">
            <svg-icon style="margin-left: 10px;" icon-class='aixin' width="25px" height="25px" class="icon"/>
          </span>
        <span @click="startRecordAudio">
            <svg-icon style="margin-left: 10px;"
                      icon-class='tubiaozhizuomobanyihuifu-'
                      width="25px" height="25px"
                      class="icon"/>
          </span>
        <span @click="moreShow=!moreShow">
            <svg-icon style="margin-left: 10px;" icon-class='jiahao' width="25px" height="25px" class="icon"/>
        </span>
      </div>
      <div v-if="moreShow" class="moreFun">
        <emoji :emojiList="emojiList" @emojiStr="emojiStrFn"></emoji>
      </div>
    </div>
  </div>
</template>
<!--http://127.0.0.1:9090/audio/1682860887674.wav-->
<script>
import { addCoverAPI, getChatsAllAPI, getChatsAudioAPI, getUserInfoAPI } from '@/api'
import dayjs from 'dayjs'
import emoji from '../components/emoji.vue'
import Recorder from 'js-audio-recorder'

export default {
  name: 'loverIndex',
  components: {
    emoji
  },
  data () {
    return {
      userInfo: {},
      loverInfo: [],
      chatDataArr: [],
      sendMsg: '',
      moreShow: false,
      myId: '',
      uid: '',
      emojiList: '',
      isOnline: false,
      isLoverLogin: false,
      recorder: new Recorder({
        sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
        sampleRate: 16000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
        numChannels: 1 // 声道，支持 1 或 2， 默认是1
        // compiling: false,(0.x版本中生效,1.x增加中)  // 是否边录边转换，默认是false
      }),
      isAudioShow: false,
      audioData: '',
      duration: ''
    }
  },
  filters: {
    // 定义局部过滤器
    toTime (time) {
      const today = dayjs()
      const createTime = dayjs(time)
      if (today.diff(createTime, 'day') > 0) {
        // 时间早于今天
        return createTime.format('MM-DD HH:mm')
      } else {
        // 时间等于或晚于今天
        return createTime.format('HH:mm')
      }
    }
  },
  created () {
    this.loadUserInfo()
  },
  mounted () {
    this.scrollBottom()
  },
  updated () {
    this.scrollBottom()
  },
  beforeDestroy () {
    this.$socket.emit('userLogout', this.loverInfo.username)
  },
  /* socket是监听服务器发布的自定义事件 */
  sockets: {
    /* 监听couple事件 */
    couple: function (data) {
      console.log('couple data 数据返回 = >', data)
      this.chatDataArr.push(data)
    },
    /* 监听couple事件 */
    selfInfo: function (data) {
      this.isLoverLogin = data
      console.log(data)
    }
  },
  methods: {
    // 请求用户信息
    async loadUserInfo () {
      try {
        const res = await getUserInfoAPI()
        console.log(res)
        this.userInfo = res.data.data
        this.loverInfo = res.data.loverData
        this.$socket.emit('selfInfo', this.userInfo.username, this.loverInfo.username)
        await this.getChatsAll()
      } catch (error) {
        console.log(error)
      }
    },
    // 发送文本信息
    send () {
      // if (this.sendMsg) {
      const selfMsgData = {
        contentImg: '',
        name: this.userInfo.username,
        content: this.sendMsg,
        emojiList: this.emojiList,
        img: this.userInfo.user_pic,
        time: new Date(),
        loverName: this.loverInfo.username,
        user_id: this.userInfo.id,
        lover_id: this.userInfo.lover_id,
        audioData: this.audioData,
        duration: this.duration
      }
      this.$socket.emit('couple', selfMsgData)
      this.sendMsg = ''
      this.emojiList = ''
      this.audioData = ''
    },
    // },
    scrollBottom () {
      this.$nextTick(() => {
        const chatRoom = this.$refs.chatRoom
        chatRoom.parentNode?.scrollTo(0,
          chatRoom.getBoundingClientRect().height - chatRoom.parentNode.getBoundingClientRect().height
        )
        // console.log(chatRoom.scrollTop)
        // console.log('scrollHeight', chatRoom.scrollHeight)
      })
    },
    // 发送图片
    async onFileChange () {
      // 将输入框中的图片存储到数据中
      // 1. 获取文件对象
      const file = this.$refs.file.files[0]
      // 此时可以自行将文件上传至服务器
      const imgFile = new FormData()
      imgFile.append('fileType', 'IMAGE')
      imgFile.append('file', file)
      const { data: res } = await addCoverAPI(imgFile)

      const selfMsgData = {
        contentImg: res.url,
        name: this.userInfo.username,
        content: this.sendMsg,
        emojiList: this.emojiList,
        img: this.userInfo.user_pic,
        time: new Date(),
        loverName: this.loverInfo.username,
        user_id: this.userInfo.id,
        lover_id: this.userInfo.lover_id,
        audioData: this.audioData,
        duration: this.duration
      }
      this.$socket.emit('couple', selfMsgData)

      // 3. 每次获取完成图片后要清空文件上传框中的数据
      this.$refs.file.value = ''
    },
    // 接收表情字符串
    emojiStrFn (emojiStr) {
      this.emojiList = emojiStr
    },
    // 获取聊天记录
    async getChatsAll () {
      const { data: res } = await getChatsAllAPI({
        user_id: this.userInfo.id,
        lover_id: this.userInfo.lover_id
      })
      this.chatDataArr = res.message.sort(function (a, b) {
        return dayjs(a.time).isBefore(dayjs(b.time)) ? -1 : 1
      }).slice(-10)
      console.log(this.chatDataArr)
    },
    playAudio () {
      this.$refs.audio[0].play()
    },
    // 开始录音
    startRecordAudio () {
      this.isAudioShow = true
      Recorder.getPermission().then(
        () => {
          console.log('开始录音')
          this.recorder.start() // 开始录音
        },
        (error) => {
          this.$message({
            message: '请先允许该网页使用麦克风',
            type: 'info'
          })
          console.log(`${error.name} : ${error.message}`)
        }
      )
    },
    //   结束录音
    async stopRecordAudio () {
      this.recorder.stop()
      this.isAudioShow = false

      // 上传wav录音数据
      const wavBlob = this.recorder.getWAVBlob()
      // 创建一个formData对象
      const formData = new FormData()
      // 此处获取到blob对象后需要设置fileName满足当前项目上传需求，其它项目可直接传把blob作为file塞入formData
      const newbolb = new Blob([wavBlob], { type: 'audio/wav' })
      // 获取当时时间戳作为文件名
      const fileOfBlob = new File([newbolb], new Date().getTime() + '.wav')
      formData.append('file', fileOfBlob)
      const { data: res } = await getChatsAudioAPI(formData)
      this.audioData = res
      this.duration = this.recorder.duration.toFixed(2)
      //  发送socket
      const selfMsgData = {
        contentImg: '',
        name: this.userInfo.username,
        content: this.sendMsg,
        emojiList: this.emojiList,
        img: this.userInfo.user_pic,
        time: new Date(),
        loverName: this.loverInfo.username,
        user_id: this.userInfo.id,
        lover_id: this.userInfo.lover_id,
        audioData: this.audioData,
        duration: this.duration
      }
      this.$socket.emit('couple', selfMsgData)
    }

  }
}
</script>

<style scoped lang="less">
.lover-container {
  height: 100vh;
  background-color: #f6f6f6;
  overflow: hidden;

  .van-nav-bar {
    height: 55px;
    border-radius: 0 0 20px 20px;

    &::after {
      border: none;
    }
  }

  .mainWrap {
    //background-color: pink;
    height: 82vh;
    position: absolute;
    width: 100%;
    margin-top: 58px;
    overflow-y: auto;

    .main {
      padding-bottom: 30px;

      .msg {
        font-size: 13px;
        display: flex;
        padding: 25px 20px 0 20px;
        flex-wrap: wrap;

        .conWrap {

          .content {
            color: black;
            max-width: 200px;
            margin-left: 10px;
            padding: 7px;
            border-radius: 0 10px 10px 10px;
            background-color: #fff;
            letter-spacing: .5px;
            font-family: "微软雅黑", sans-serif;
            word-break: break-all;
          }

          .msgTime {
            font-size: 12px;
            padding: 5px 0px 0px 15px;
          }
        }
      }

      .rightPerson {
        display: flex;
        flex-direction: row-reverse;
        flex-wrap: wrap;

        .conWrap {
          .content {
            color: #fff;
            max-width: 200px;
            margin-right: 10px;
            border-radius: 10px 0px 10px 10px;
            background-color: #eb6282;
            word-break: break-all;
          }

          .msgTime {
            float: right;
            padding: 5px 15px 0px 0px;
          }
        }
      }
    }
  }

  .foot {
    background-color: #fff;
    position: fixed;
    bottom: 0;
    width: 100%;
    border-radius: 20px 20px 0px 0px;

    .inputBox {
      height: 60px;
      display: flex;
      justify-content: center;
      align-items: center;

      input {
        font-size: 14px;
        height: 30px;
        padding: 0px 10px;
        width: 200px;
        border: none;
      }
    }

    .moreFun {
      padding: 15px;
      transition: all 2s;
      font-size: 12px;
    }
  }

  .wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;

    span {
      font-size: 14px;
      color: #fff;
    }
  }
}
</style>
